//
//  MYGCommunityQuestionController.swift
//  MYGrow
//
//  Created by lance on 2024/3/3.
//

import UIKit
import MJRefresh

class MYGCommunityQuestionController: MYGBaseController {
    // MARK: - Property
    var communityId: Int = 0
    var model: MYGCommunityDetailModel?
    var isMyAnswer: Bool = false
    // MARK: - life cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        configUI()
        scrollView.mj_header?.beginRefreshing()
        NotificationCenter.default.addObserver(self, selector: #selector(reloadMyAnswerData), name: NSNotification.Name.init("reloadAnswerList"), object: nil)
    }
    
    // MARK: - UI
    private func configUI() {
        title = "信息详情"
        view.backgroundColor = .white
        
        
        let rightBar = UIBarButtonItem(image: UIImage.init(named: "MYG_cloudDisk_like_share"), style: .plain, target: self, action: #selector(clickShareBtn))
        rightBar.tintColor = .black
        self.navigationItem.rightBarButtonItem = rightBar

        
        view.addSubview(scrollView)
        scrollView.addSubview(cardContentView)
        cardContentView.addSubviews([
            infoView,
            answerView,
            sperator
        ])
        
        scrollView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.left.right.bottom.equalToSuperview()
        }
        
        cardContentView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(15)
            make.left.right.equalToSuperview().inset(15)
            make.width.equalTo(screenWidth-30)
            make.bottom.equalToSuperview().offset(-15)
        }
        
        infoView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
        }
        
        answerView.snp.makeConstraints { make in
            make.top.equalTo(infoView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        
        sperator.snp.makeConstraints { make in
            make.bottom.equalTo(infoView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(0.5)
        }
        
        
    }
    
    private func loadData() {
        MYGNetwork<MYGCommunityApi, MYGCommunityDetailModel>.request(target: .detail(id: communityId)) {[weak self] result in
            self?.model = result
            self?.updateUI()
            self?.scrollView.mj_header?.endRefreshing()
        } failed: {[weak self] _, error in
            self?.scrollView.mj_header?.endRefreshing()
            MMYGHUD.showToast(self?.view, text: error)
        }
    }
    
    private func updateUI() {
        cardContentView.isHidden = false
        //answerButton.isHidden = (model?.answer.count ?? 0) != 0
        infoView.model = model
        answerView.model = model
    }
    
    // MARK: - lazy load
    private lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.mj_header = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
            self?.loadData()
        })
        return scrollView
    }()
    
    private lazy var cardContentView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = 5
        view.clipsToBounds = false
        view.layerShadowColor = .rgba(0, 0, 0, 0.1)
        view.layerShadowOffset = CGSize(width: 0, height: 0)
        view.layerShadowOpacity = 1
        view.layerShadowRadius = 5
        view.isHidden = true
        return view
    }()
    
    private lazy var infoView: MYGCommunityQuestionInfoView = {
        let view = MYGCommunityQuestionInfoView(frame: .zero)
        return view
    }()
    
    private lazy var answerView: MYGCommunityQuestionAnswerView = {
        let view = MYGCommunityQuestionAnswerView()
        view.isMyAnswer = isMyAnswer
        view.action = { [self] type in
            if type == 0 { // 聊天
                if isMyAnswer == true {
                    delMyAnswer()
                }else {
                    let phone = "\(self.model?.doctor?.phone ?? "")1"
                    let vc =  MYGChatController(sessionId: 0, mobile: phone, mo_shenggx: 0, title: self.model?.doctor?.name ?? "")
                    self.navigationController?.pushViewController(vc)
                }
            } else if type == 1 { // 点赞
                self.listItemDidClickLike()
            } else if type == 2 { // 收藏
                self.listItemDidClickStar()
            }
            
        }
        return view
    }()
    
    private lazy var sperator: UIView = {
        let view = UIView()
        view.backgroundColor = .rgba(238, 238, 238)
        return view
    }()
    
}

extension MYGCommunityQuestionController {
    
    @objc func clickShareBtn(){
        
    }
  
    @objc func reloadMyAnswerData(){
        loadData()
    }
}


extension MYGCommunityQuestionController {
    
    private func delMyAnswer(){
        guard let model = model else { return }
        MYGLoading.show()
        MYGNetwork<MYGCommunityApi,MYGEmptyModel>.request(target: .delMyAnswer(id: "\(model.id)")) { [self] _ in
            MYGLoading.hide()
            navigationController?.popViewController(animated: true)
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    private func listItemDidClickLike() {
        guard let model = model else { return }
        let likeStatus = model.is_like == 0 ? "1" : "0"
        MYGLoading.show(self.view)
        
//        MYGNetwork<MYGMeAPI, MYGEmptyModel>.request(target: .like(param: [
//            "id":model.id,"like_status":likeStatus
//           ])) { [weak self] item in
//               guard let self = self else { return }
//               MYGLoading.hide(self.view)
//   //            guard let response = response else { return }
//               if model.is_like == 1 {
//                   self.model?.like_count = model.like_count - 1
//                   self.model?.is_like = 0
//               } else {
//                   self.model?.like_count = model.like_count + 1
//                   self.model?.is_like = 1
//               }
//               self.updateUI()
//               
//       } failed: { _, error in
//           MYGLoading.hide(self.view)
//           MMYGHUD.showToast(text: error)
//       }
        
        MMYGNetwork<MYGCommunityApi, MYGEmptyModel>.request(target: .like(type: "12", likeStatus: likeStatus, id: String(model.id))) {[weak self] response in
            guard let self = self else { return }
            MYGLoading.hide(self.view)
            guard let response = response else { return }
            if model.is_like == 1 {
                self.model?.like_count = model.like_count - 1
                self.model?.is_like = 0
            } else {
                self.model?.like_count = model.like_count + 1
                self.model?.is_like = 1
            }
            self.updateUI()
        } failed: {[weak self] _, error in
            MYGLoading.hide(self?.view)
            MMYGHUD.showToast(text: error)
        }
    }
    
    private func listItemDidClickStar() {
        guard let model = model else { return }
        var collectionStatus = "1"
        if model.is_collect == 0 {
            collectionStatus = "1"
        }else {
            collectionStatus = "0"
        }
        MYGLoading.show(self.view)
        
        MYGNetwork<MYGMeAPI, MYGEmptyModel>.request(target: .collectSubmit(param: [
            "data_id":"\(model.id)",
           "type":"17", 
            "collect_status":collectionStatus])) { item in
                MYGLoading.hide(self.view)
                if model.is_collect == 1 {
                    self.model?.collect_count = model.collect_count - 1
                    self.model?.is_collect = 0
                } else {
                    self.model?.collect_count = model.collect_count + 1
                    self.model?.is_collect = 1
                }
                self.updateUI()
            } failed: { _, error in
                MYGLoading.hide(self.view)
           MMYGHUD.showToast(text: error)
       }
        
        
//        MYGNetwork<MYGCommunityApi, MYGEmptyModel>.request(target: model.is_collect == 0 ? .collect(id: String(model.id)): .uncollect(id:String(model.id))) { result in
//            MYGLoading.hide(self.view)
//            if model.is_collect == 1 {
//                self.model?.collect_count = model.collect_count - 1
//                self.model?.is_collect = 0
//            } else {
//                self.model?.collect_count = model.collect_count + 1
//                self.model?.is_collect = 1
//            }
//        } failed: { _, error in
//            MYGLoading.hide(self.view)
//            MMYGHUD.showToast(text: error)
//        }
    }
    
}
